const API_BASE_URL = '/api/orders';

// DOM 元素
const orderListSection = document.getElementById('order-list');
const createOrderSection = document.getElementById('create-order');
const editOrderSection = document.getElementById('edit-order');
const orderDetailsSection = document.getElementById('order-details');
const ordersTableBody = document.querySelector('#orders-table tbody');
const createOrderForm = document.getElementById('create-order-form');
const editOrderForm = document.getElementById('edit-order-form');
const refreshBtn = document.getElementById('refresh-btn');
const editOrderBtn = document.getElementById('edit-order-btn');
const submitOrderBtn = document.getElementById('submit-order-btn');
const approveOrderBtn = document.getElementById('approve-order-btn');
const rejectOrderBtn = document.getElementById('reject-order-btn');
const closeOrderBtn = document.getElementById('close-order-btn');
const deleteOrderBtn = document.getElementById('delete-order-btn');
const backBtn = document.getElementById('back-btn');
const cancelEditBtn = document.getElementById('cancel-edit');

let currentOrderId = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载订单列表
    loadOrders();
    
    // 导航链接事件监听
    document.querySelector('a[href="index.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'index.html';
    });
    
    document.querySelector('a[href="supplier.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'supplier.html';
    });
    
    document.querySelector('a[href="product.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'product.html';
    });
    
    document.querySelector('a[href="#order-list"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(orderListSection);
        hideElement(orderDetailsSection);
    });
    
    document.querySelector('a[href="#create-order"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(createOrderSection);
        hideElement(orderDetailsSection);
    });
    
    // 刷新按钮事件监听
    refreshBtn.addEventListener('click', loadOrders);
    
    // 创建订单表单提交事件监听
    createOrderForm.addEventListener('submit', function(e) {
        e.preventDefault();
        createOrder();
    });
    
    // 编辑订单表单提交事件监听
    editOrderForm.addEventListener('submit', function(e) {
        e.preventDefault();
        updateOrder();
    });
    
    // 详情页面按钮事件监听
    backBtn.addEventListener('click', function() {
        showSection(orderListSection);
        hideElement(orderDetailsSection);
    });
    
    editOrderBtn.addEventListener('click', function() {
        if (currentOrderId) {
            showEditForm(currentOrderId);
        }
    });
    
    cancelEditBtn.addEventListener('click', function() {
        showSection(orderListSection);
        hideElement(editOrderSection);
    });
    
    submitOrderBtn.addEventListener('click', function() {
        if (currentOrderId) {
            submitOrder(currentOrderId);
        }
    });
    
    approveOrderBtn.addEventListener('click', function() {
        if (currentOrderId) {
            approveOrder(currentOrderId);
        }
    });
    
    rejectOrderBtn.addEventListener('click', function() {
        if (currentOrderId) {
            rejectOrder(currentOrderId);
        }
    });
    
    closeOrderBtn.addEventListener('click', function() {
        if (currentOrderId) {
            closeOrder(currentOrderId);
        }
    });
    
    deleteOrderBtn.addEventListener('click', function() {
        if (currentOrderId && confirm('确定要删除该订单吗？')) {
            deleteOrder(currentOrderId);
        }
    });
});

// 显示指定的部分，隐藏其他部分
function showSection(section) {
    orderListSection.classList.add('hidden');
    createOrderSection.classList.add('hidden');
    editOrderSection.classList.add('hidden');
    orderDetailsSection.classList.add('hidden');
    
    section.classList.remove('hidden');
}

// 隐藏元素
function hideElement(element) {
    element.classList.add('hidden');
}

// 显示编辑表单
function showEditForm(orderId) {
    fetch(`${API_BASE_URL}/${orderId}`)
        .then(response => response.json())
        .then(order => {
            // 填充表单数据
            document.getElementById('edit-order-id').value = order.id;
            document.getElementById('edit-supplier-id').value = order.supplierID;
            document.getElementById('edit-order-date').value = order.orderDate.split(' ')[0];
            document.getElementById('edit-order-status').value = order.status;
            document.getElementById('edit-order-remark').value = order.remark || '';
            
            // 显示编辑表单
            showSection(editOrderSection);
        })
        .catch(error => {
            console.error('获取订单信息失败:', error);
            alert('获取订单信息失败: ' + error.message);
        });
}

// 更新订单
function updateOrder() {
    const orderId = document.getElementById('edit-order-id').value;
    const orderData = {
        id: orderId,
        supplierID: parseInt(document.getElementById('edit-supplier-id').value),
        orderDate: document.getElementById('edit-order-date').value,
        status: document.getElementById('edit-order-status').value,
        remark: document.getElementById('edit-order-remark').value
    };

    fetch(`${API_BASE_URL}/${orderId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(orderData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('更新订单失败');
        }
        return response.json();
    })
    .then(order => {
        alert('订单更新成功');
        showSection(orderListSection);
        loadOrders();
    })
    .catch(error => {
        console.error('更新订单失败:', error);
        alert('更新订单失败: ' + error.message);
    });
}

// 日期时间格式化
function formatDateTime(dateTime) {
    if (!dateTime) return '';
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN');
}

// 获取状态显示文本
function getStatusText(status) {
    const statusMap = {
        'DRAFT': '草稿',
        'SUBMITTED': '已提交',
        'APPROVED': '已批准',
        'REJECTED': '已拒绝',
        'CLOSED': '已关闭'
    };
    return statusMap[status] || status;
}

// 获取状态样式类名
function getStatusClassName(status) {
    return `status-badge status-${status}`;
}

// 加载所有订单
function loadOrders() {
    fetch(API_BASE_URL)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(orders => {
            renderOrdersTable(orders);
        })
        .catch(error => {
            console.error('加载订单失败:', error);
            alert('加载订单失败: ' + error.message);
            // 使用mock数据
            renderOrdersTable(mockOrders);
        });
}

// 渲染订单表格
function renderOrdersTable(orders) {
    ordersTableBody.innerHTML = '';
    
    if (!orders || orders.length === 0) {
        ordersTableBody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无订单数据</td></tr>';
        return;
    }
    
    orders.forEach(order => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${order.id}</td>
            <td>${order.orderNumber}</td>
            <td>${order.supplierID}</td>
            <td>¥${(order.totalAmount || 0).toFixed(2)}</td>
            <td>${order.orderDate.split(' ')[0]}</td>
            <td class="${getStatusClassName(order.status)}">${getStatusText(order.status)}</td>
            <td>${formatDateTime(order.creationTime)}</td>
            <td>
                <button class="btn btn-sm btn-primary view-details-btn" data-id="${order.id}">查看</button>
            </td>
        `;
        ordersTableBody.appendChild(row);
    });
    
    // 添加查看详情的事件监听
    document.querySelectorAll('.view-details-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const orderId = this.getAttribute('data-id');
            getOrderById(orderId);
        });
    });
}

// 创建订单
function createOrder() {
    const orderData = {
        supplierID: parseInt(document.getElementById('supplier-id').value),
        orderDate: document.getElementById('order-date').value,
        status: document.getElementById('order-status').value,
        remark: document.getElementById('order-remark').value
    };

    fetch(API_BASE_URL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(orderData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('创建订单失败');
        }
        return response.json();
    })
    .then(order => {
        alert('订单创建成功');
        createOrderForm.reset();
        showSection(orderListSection);
        loadOrders();
    })
    .catch(error => {
        console.error('创建订单失败:', error);
        alert('创建订单失败: ' + error.message);
    });
}

// 根据ID获取订单
function getOrderById(orderId) {
    fetch(`${API_BASE_URL}/${orderId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取订单失败');
            }
            return response.json();
        })
        .then(order => {
            displayOrderDetails(order);
        })
        .catch(error => {
            console.error('获取订单失败:', error);
            alert('获取订单失败: ' + error.message);
        });
}

// 显示订单详情
function displayOrderDetails(order) {
    currentOrderId = order.id;
    
    document.getElementById('detail-id').textContent = order.id;
    document.getElementById('detail-order-number').textContent = order.orderNumber;
    document.getElementById('detail-supplier-id').textContent = order.supplierID;
    document.getElementById('detail-total-amount').textContent = '¥' + (order.totalAmount || 0).toFixed(2);
    document.getElementById('detail-order-date').textContent = order.orderDate.split(' ')[0];
    document.getElementById('detail-status').textContent = getStatusText(order.status);
    document.getElementById('detail-created-time').textContent = formatDateTime(order.creationTime);
    document.getElementById('detail-updated-time').textContent = formatDateTime(order.updateTime);
    document.getElementById('detail-remark').textContent = order.remark || '';
    
    // 更新状态样式
    document.getElementById('detail-status').className = getStatusClassName(order.status);
    
    showSection(orderDetailsSection);
}

// 提交订单
function submitOrder(orderId) {
    fetch(`${API_BASE_URL}/${orderId}/submit`, {
        method: 'PUT'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('提交订单失败');
        }
        return response.json();
    })
    .then(order => {
        alert('订单已提交');
        displayOrderDetails(order);
        loadOrders();
    })
    .catch(error => {
        console.error('提交订单失败:', error);
        alert('提交订单失败: ' + error.message);
    });
}

// 批准订单
function approveOrder(orderId) {
    fetch(`${API_BASE_URL}/${orderId}/approve`, {
        method: 'PUT'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('批准订单失败');
        }
        return response.json();
    })
    .then(order => {
        alert('订单已批准');
        displayOrderDetails(order);
        loadOrders();
    })
    .catch(error => {
        console.error('批准订单失败:', error);
        alert('批准订单失败: ' + error.message);
    });
}

// 拒绝订单
function rejectOrder(orderId) {
    fetch(`${API_BASE_URL}/${orderId}/reject`, {
        method: 'PUT'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('拒绝订单失败');
        }
        return response.json();
    })
    .then(order => {
        alert('订单已拒绝');
        displayOrderDetails(order);
        loadOrders();
    })
    .catch(error => {
        console.error('拒绝订单失败:', error);
        alert('拒绝订单失败: ' + error.message);
    });
}

// 关闭订单
function closeOrder(orderId) {
    fetch(`${API_BASE_URL}/${orderId}/close`, {
        method: 'PUT'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('关闭订单失败');
        }
        return response.json();
    })
    .then(order => {
        alert('订单已关闭');
        displayOrderDetails(order);
        loadOrders();
    })
    .catch(error => {
        console.error('关闭订单失败:', error);
        alert('关闭订单失败: ' + error.message);
    });
}

// 删除订单
function deleteOrder(orderId) {
    fetch(`${API_BASE_URL}/${orderId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('删除订单失败');
        }
        alert('订单已删除');
        showSection(orderListSection);
        loadOrders();
    })
    .catch(error => {
        console.error('删除订单失败:', error);
        alert('删除订单失败: ' + error.message);
    });
}

// Mock数据
const mockOrders = [
    {
        id: 1,
        orderNumber: 'PO202301001',
        supplierID: 1,
        totalAmount: 29990.00,
        orderDate: '2023-04-01',
        status: 'APPROVED',
        creationTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        remark: '紧急订单'
    },
    {
        id: 2,
        orderNumber: 'PO202301002',
        supplierID: 2,
        totalAmount: 119980.00,
        orderDate: '2023-04-05',
        status: 'SUBMITTED',
        creationTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        remark: '批量采购'
    },
    {
        id: 3,
        orderNumber: 'PO202301003',
        supplierID: 3,
        totalAmount: 49980.00,
        orderDate: '2023-04-10',
        status: 'DRAFT',
        creationTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        remark: '测试订单'
    }
];